import { reactive} from 'vue'
import { defineStore } from "pinia"
import { removeCookie } from '../utils/cookies';
import { home, getTagOptions, getEntranceTicket, share } from './mobile'
import { login, userInfo } from './pcApi'

/**
 * 移动端
 */
export const useMobileStore = defineStore("mobile", {
  state: () => reactive({
    lock: false, // 用户锁，限制提交次数
    status: 0, // 当前状态 0 预热 1 进行中 2 已结束
    count: 1,
    index: {
      background_cover: '', // 视频封面图
      background_mp4:'', // 视频URL
      join_virtually: 0, // 申请加入人数
      open_time: '', // 开启时间
      open_time_unix: '', // 开启时间戳
      persion: [], // 参与人头像group
      platform: [], // 平台
      reservation_qrcode: '', // 预约二维码
    },
    user: {
      nickname: null, //昵称(最多6)
      sex: 1,//性别 1 男 2 女
      tag_id: null, //标签id
      want: null, // 本次大会愿景期待
    },
    shareParam: {
      appId: '',
      nonceStr: '',
      signature: '',
      timestamp: ''
    }
  }),
  getters: {
    async init(state) {
      const response = await home()
      state.index = response
      return response
    },
    tag() {
      const response = getTagOptions()
      return response
    },    
  },
  actions: {
    saveToImg(option){
      return getEntranceTicket(option).then(res => {
        return res
      }).catch(_ => {console.log(_)})
    },
    share(option) {
      return share(option). then(res => {
        return res
      })
    },
    clearUserInfo() {
      this.user = {
        nickname: null, //昵称(最多6)
        sex: 1,//性别 1 男 2 女
        tag_id: null, //标签id
        want: null, // 本次大会愿景期待
      }
    }
  }
},
{
  persist: { // 数据持久化
    storage: window.sessionStorage,
    paths: ["user.nickname", "user.sex", "user.tag_id", "user.want"]
  }
})

export const useLoginStore = defineStore("login", {
  state: () => reactive({
    userinfo: {
      nickname: '',
      username: '',
      avatar: '',
      address: '',
      birthday: '',
      mobile: '',
      cover: '',
      password: '',
      sex: 0,
      count: '',
      medalId: '',
      medalList: [],
      provinceId: '',
      cityId: '',
      remark: '',
    }
  }),
  getters: {
    getUserinfo(state) {
      return state.userinfo;
    }
  },
  actions: {
    async fetchUserInfo() {
      try {
        const res = await userInfo(); // 假设 userInfo() 返回一个 Promise
        this.userinfo = res; // 更新状态中的 userinfo 数据
      } catch (e) {
        console.error('Failed to fetch user info:', e);
      }
    },
    logout() {
      removeCookie('token');
      this.userinfo = {
        nickname: '',
        avatar: ''
      }
    }
  },
  persist: true
})